package org.example.websocket;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpServerCodec;
import io.netty.handler.codec.http.websocketx.WebSocketServerProtocolHandler;
import io.netty.handler.logging.LogLevel;
import io.netty.handler.logging.LoggingHandler;
import io.netty.handler.stream.ChunkedWriteHandler;

/**
 * @author xuan
 * @create 2023/9/18
 */
public class MyServer {
    private static int port = 8080;

    public static void main(String[] args) {
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup();

        try {
            ServerBootstrap serverBootstrap = new ServerBootstrap();
            serverBootstrap.group(bossGroup, workerGroup)
                    .channel(NioServerSocketChannel.class)
                    .handler(new LoggingHandler(LogLevel.INFO)) //在bossGroup增加一个日志处理器
                    .childHandler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel sc) throws Exception {
                            ChannelPipeline pipeline = sc.pipeline();

                            //因为基于http协议，因此我们要使用http的编码和解码器
                            pipeline.addLast(new HttpServerCodec());
                            //是以块方式写的，需要添加ChunkedWriteHandler处理器
                            pipeline.addLast(new ChunkedWriteHandler());
                            /**
                             * 说明：
                             *      1.因为http数据在传输过程中是会分段的，而HttpObjectAggregator可以将多个段聚合起来，这就是为什么当浏览器发送大量数据时，就会发出多次http请求
                             * */
                            pipeline.addLast(new HttpObjectAggregator(8192));
                            /**
                             * 说明：
                             *      1.对于WebSocket，它的数据是以帧（frame）的形式传递的，可以看到WebSocketFrame下面有六个子类
                             *      2.浏览器发送请求它的形式 ws://localhost:8080/hello 表示请求的url
                             *      3.WebSocketServerProtocolHandler的核心功能是将我们的http协议升级成ws协议，已实现保持长连接的作用
                             * */
                            pipeline.addLast(new WebSocketServerProtocolHandler("/hello"));
                            //写一个自定义的handler，是我们真正的处理业务逻辑的，去处理客户端发送来的请求
                            pipeline.addLast(new MyTestWebSocketFrameHandler());
                        }
                    });

            ChannelFuture future = serverBootstrap.bind(port).sync();
            future.channel().closeFuture().sync();

        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
